package com.bidevalution.controller.api;

import com.bidevalution.business.service.BeBidResultService;
import com.bidevalution.business.service.BeSectionInfoService;
import com.bidevalution.dao.entity.BeSectionInfo;
import com.bidevalution.support.context.Constants;
import com.qtp.core.model.Response;
import com.qtp.core.util.GsonUtil;
import com.qtp.core.util.IdsUtil;
import com.qtp.core.util.OConvertUtils;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 中标结果推送相关接口
 * Created by glodon on 2019-11-18.
 */
@RestController
@RequestMapping("/beBidReuslt")
@Api("中标结果推送")
public class BeBidResultController {
    private static final Logger log = LoggerFactory.getLogger(BeBidResultController.class);
    @Autowired
    private BeBidResultService beBidResultService;
    @Autowired
    private BeSectionInfoService beSectionInfoService;
    @Value("${download.file.path}")
    private String downloadFileUrl;
    /**
     * 根据主键获取标段信息
     *
     * @param sectionId
     * @return
     */
    @ApiOperation(value = "中标结果推送--查询项目信息(2019-11-19-v1)", response = Response.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sectionId", value = "标段信息主键", dataType = "String", paramType = "query", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = Constants.FIVE_HUNDRED_AND_ONE, message = "参数不可以为空"),
    })
    @GetMapping(value = "/getSectionInfo")
    @ResponseBody
    public Response<Map<String, Object>> getSectionInfo(@RequestParam("sectionId") String sectionId) {
        if (StringUtils.isBlank(sectionId)) {
            return Response.fail("参数不可以为空", Constants.FIVE_HUNDRED_AND_ONE);
        }
        try {
            return Response.ok(beBidResultService.getProjectInfo(sectionId));
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            return Response.fail("查询项目信息失败");
        }
    }

    /**
     * 更新项目信息
     *
     * @param map
     * @return
     */
    @ApiOperation(value = "中标结果推送--更新项目信息(2019-11-22-v1)", response = Response.class)
    @PostMapping(value = "/updateSectionInfo")
    @ApiImplicitParam(name = "sectionInfo" , paramType = "body",examples = @Example({
            @ExampleProperty(value = "{'sectionCode':'XXXX','objectionType':'XXXX'}", mediaType = "application/json")
    }))
    @ResponseBody
    public Response<List<Map<String, Object>>> updateSectionInfo(
            @RequestBody @ApiParam(name = "sectionInfo", value = "传入json格式", required = true) Map<String,Object> map) {
        try {
            beBidResultService.updateProjectInfo(map);
            return Response.ok();
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            return Response.fail("更新项目信息失败");
        }
    }

    /**
     * 查询中标单位列表
     *
     * @param sectionId
     * @return
     */
    @ApiOperation(value = "中标结果推送--查询中标单位列表(2019-11-19-v1)", response = Response.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sectionId", value = "标段信息主键", dataType = "String", paramType = "query", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = Constants.FIVE_HUNDRED_AND_ONE, message = "参数不可以为空"),
    })
    @GetMapping(value = "/getBidInfoList")
    @ResponseBody
    public Response<List<Map<String, Object>>> getBidInfoList(@RequestParam("sectionId") String sectionId) {
        if (StringUtils.isBlank(sectionId)) {
            return Response.fail("参数不可以为空", Constants.FIVE_HUNDRED_AND_ONE);
        }
        try {
            return Response.ok(beBidResultService.getBidInfoList(sectionId));
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            return Response.fail("查询中标单位列表失败");
        }
    }

    /**
     * 更新中标单位业绩列表
     *
     * @param map
     * @return
     */
    @ApiOperation(value = "中标结果推送--更新中标单位列表(2019-11-20-v1)", response = Response.class)
    @PostMapping(value = "/updateBidInfoList")
    @ResponseBody
    public Response<List<Map<String, Object>>> updateBidInfoList(
            @RequestBody @ApiParam(name = "bidInfoList", value = "传入json格式", required = true) List<Map<String,Object>> map) {
        try {
            beBidResultService.updateBidInfoList(map);
            return Response.ok();
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            return Response.fail("更新中标单位列表失败");
        }
    }

    /**
     * 查询中标单位业绩列表
     *
     * @param enterpriseId
     * @return
     */
    @ApiOperation(value = "中标结果推送--查询中标单位业绩列表(2019-11-19-v1)", response = Response.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "enterpriseId", value = "单位id", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "performanceType", value = "业绩类型，0，资格，1 评分", dataType = "String", paramType = "query", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = Constants.FIVE_HUNDRED_AND_ONE, message = "参数不可以为空"),
    })
    @GetMapping(value = "/getBidPerformanceList")
    @ResponseBody
    public Response<List<Map<String, Object>>> getBidPerformanceList(@RequestParam("enterpriseId") String enterpriseId,@RequestParam("performanceType") String performanceType) {
        if (StringUtils.isBlank(enterpriseId)||StringUtils.isBlank(performanceType)) {
            return Response.fail("参数不可以为空", Constants.FIVE_HUNDRED_AND_ONE);
        }
        try {
            return Response.ok(beBidResultService.getBidPerformanceList(enterpriseId,performanceType));
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            return Response.fail("查询中标单位业绩失败");
        }
    }
    /**
     * 新增_修改业绩信息
     */
    @ApiOperation(value = "新增_修改业绩信息", response = Response.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "requestType", value = "请求类型0:新增1:修改", dataType = "String", paramType = "query",required = true),
            @ApiImplicitParam(name = "performanceId", value = "业绩id（新增不需要传会自动生成，修改必须传）", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "enterpriseId", value = "单位id", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "performanceCertify", value = "该业绩证明对象",dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "performanceName", value = "业绩名称",dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "unitName", value = "建设单位（项目业主）",dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "requirements", value = "业绩和各指标要求",dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "beweismaterial", value = "证明材料",dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "bidFileLocation", value = "投标文件的位置",dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "conclusion", value = "评审结论",dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "memo", value = "专家评审意见(为空是符合，不为空是不符合)",dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "ispush", value = "是否推送（1：推送，0：不推送）",dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "performanceType", value = "业绩类型，0，资格，1 评分", dataType = "String", paramType = "query", required = true)
    })
    @PostMapping(value = "/insertPerformance")
    public Response insertPerformance( @RequestParam(name = "performanceId",required = false) String performanceId,
                                       @RequestParam("requestType") String requestType,
                                       @RequestParam("enterpriseId") String enterpriseId,
                                       @RequestParam("performanceCertify") String performanceCertify,
                                       @RequestParam("performanceName") String performanceName,
                                       @RequestParam("unitName") String unitName,
                                       @RequestParam("requirements") String requirements,
                                       @RequestParam("beweismaterial") String beweismaterial,
                                       @RequestParam("bidFileLocation") String bidFileLocation,
                                       @RequestParam("conclusion") String conclusion,
                                       @RequestParam(name = "memo",required = false,defaultValue = "") String memo,
                                       @RequestParam("ispush") String ispush,
                                       @RequestParam("performanceType") String performanceType) {
        try {
            Map<String,Object> params = new HashMap<String,Object>();
            if (OConvertUtils.getInt(requestType) == 1){
                //修改
                if (OConvertUtils.isEmpty(performanceId)){
                    return Response.fail("修改时performanceId不可为空");
                }else {
                    params.put("appe_AppeID", performanceId);
                }
            }else {
                //新增
                params.put("appe_AppeID", IdsUtil.uuid());
            }
            params.put("requestType",requestType);
            params.put("appe_Type",performanceType);
            params.put("appe_ValueMA",performanceCertify);
            params.put("appe_ValueMB",performanceName);
            params.put("appe_ValueMC",unitName);
            params.put("appe_ValueMD",requirements);
            params.put("appe_ValueME",beweismaterial);
            params.put("appe_ValueMF",bidFileLocation);
            params.put("appe_ValueMG",conclusion);
            params.put("enterprise_id",enterpriseId);
            if (OConvertUtils.isNotEmpty(memo)){
                params.put("appe_memo",memo);
            }
            params.put("appe_ispush",ispush);
            if (beBidResultService.insertPerformance(params)){
                return Response.ok();
            }else {
                return Response.fail("performanceId或enterpriseId错误");
            }
        } catch (Exception e) {
            log.error("LOG[]insertPerformance[]{},error={},params={}","新增_修改业绩信息异常",GsonUtil.toJsonWithGson(e),GsonUtil.toJsonWithGson(performanceId)+";"+GsonUtil.toJsonWithGson(enterpriseId)+";"+GsonUtil.toJsonWithGson(performanceCertify)+";"+GsonUtil.toJsonWithGson(performanceName)+";"+GsonUtil.toJsonWithGson(unitName)+";"+GsonUtil.toJsonWithGson(requirements)+";"+GsonUtil.toJsonWithGson(beweismaterial)+";"+GsonUtil.toJsonWithGson(bidFileLocation)+";"+GsonUtil.toJsonWithGson(conclusion)+";"+GsonUtil.toJsonWithGson(memo)+";"+GsonUtil.toJsonWithGson(ispush)+";"+GsonUtil.toJsonWithGson(performanceType));
            return Response.fail("新增_修改业绩信息失败");
        }
    }


    /**
     * 删除业绩
     */
    @ApiOperation(value = "删除业绩", response = Response.class)
    @ApiImplicitParams({
        @ApiImplicitParam(name = "performanceIds", value = "业绩Id多个id用,分隔", dataType = "String", paramType = "query",required = true),
    })
    @PostMapping(value = "/delPerformances")
    public Response delPerformances(@RequestParam(name = "performanceIds") String performanceIds) {
        try {
            beBidResultService.delPerformances(performanceIds);
            return Response.ok();
        } catch (Exception e) {
            log.error("LOG[]delPerformances[]{},error={},params={}","删除业绩异常",GsonUtil.toJsonWithGson(e),GsonUtil.toJsonWithGson(performanceIds));
            return Response.fail("删除业绩失败！");
        }
    }
    /**
     * 获取业绩文件路径
     */
    @ApiOperation(value = "获取业绩文件路径", response = Response.class)
    @ApiImplicitParams({
        @ApiImplicitParam(name = "sectionEnterpriseId", value = "项目企业id", dataType = "String", paramType = "query",required = true),
        @ApiImplicitParam(name = "atfiAnnexType", value = "附件类型", dataType = "String", paramType = "query",required = true),
    })
    @GetMapping(value = "/getPerformanceFilePath")
    public Response getPerformanceFilePath(
            @RequestParam(name = "sectionEnterpriseId") String sectionEnterpriseId,
            @RequestParam(name = "atfiAnnexType") String atfiAnnexType
    ) {
        try {
            String s = beBidResultService.getPerformanceFilePath(sectionEnterpriseId,atfiAnnexType);
            if (OConvertUtils.isEmpty(s)) {
                return Response.fail("文件不存在！");
            }else {
                return Response.ok(String.format("%s/UploadedFile/%s?preview=1", downloadFileUrl, s));
            }
        } catch (Exception e) {
            return Response.fail("文件不存在");
        }
    }

    /**
     * 更新中标单位业绩列表
     *
     * @param map
     * @return
     */
    @ApiOperation(value = "中标结果推送--更新中标单位业绩列表(2019-11-20-v1)", response = Response.class)
    @PostMapping(value = "/updateBidPerformanceList")
    @ResponseBody
    public Response<List<Map<String, Object>>> updateBidPerformanceList(
            @RequestBody @ApiParam(name = "bidPerformanceList", value = "传入json格式", required = true) List<Map<String,Object>> map) {
        try {
            beBidResultService.updateBidPerformanceList(map);
            return Response.ok();
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            return Response.fail("更新中标单位业绩失败");
        }
    }

    /**
     * 保存中标单位业绩列表
     *
     * @param map map
     * @return Response
     */
    @ApiOperation(value = "中标结果推送--保存中标单位业绩列表", response = Response.class)
    @PostMapping(value = "/saveBidPerformanceList")
    public Response<List<Map<String, Object>>> saveBidPerformanceList(
            @RequestBody @ApiParam(name = "bidPerformanceList", value = "传入json格式", required = true) List<Map<String,Object>> map) {
        return beBidResultService.saveBidPerformanceList(map);
    }

    /**
     * 根据标段ID查询是否需要业绩
     *
     * @param sectionId
     * @return Response
     */
    @GetMapping("/isProjPerf")
    @ApiOperation(value = "根据标段ID查询是否需要业绩", response = Response.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sectionId", value = "标段id", dataType = "String", paramType = "query", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = Constants.TWO_HUNDRED, message = "是否需要业绩"),
            @ApiResponse(code = Constants.FIVE_HUNDRED_AND_ONE, message = "参数不可以为空")
    })
    public Response isProjPerf(@RequestParam("sectionId") String sectionId) {
        return beBidResultService.isProjPerf(sectionId);
    }

    /**
     * 查询否决投标的原因及依据
     *
     * @param sectionId
     * @return
     */
    @ApiOperation(value = "中标结果推送--查询否决投标单位的原因及依据(2019-11-19-v1)", response = Response.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sectionId", value = "标段信息主键", dataType = "String", paramType = "query", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = Constants.FIVE_HUNDRED_AND_ONE, message = "参数不可以为空"),
    })
    @GetMapping(value = "/getUnpassedEnterpriseList")
    @ResponseBody
    public Response<List<Map<String, Object>>> getUnpassedEnterpriseList(@RequestParam("sectionId") String sectionId) {
        if (StringUtils.isBlank(sectionId)) {
            return Response.fail("参数不可以为空", Constants.FIVE_HUNDRED_AND_ONE);
        }
        try {
            return Response.ok(beBidResultService.getUnpassedEnterpriseList(sectionId));
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            return Response.fail("查询否决投标单位的原因及依据失败");
        }
    }

    /**
     * 查询评标专家公示
     *
     * @param sectionId
     * @return
     */
    @ApiOperation(value = "中标结果推送--查询评标专家公示(2019-11-19-v1)", response = Response.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sectionId", value = "标段信息主键", dataType = "String", paramType = "query", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = Constants.FIVE_HUNDRED_AND_ONE, message = "参数不可以为空"),
    })
    @GetMapping(value = "/getSectionExpertList")
    @ResponseBody
    public Response<List<Map<String, Object>>> getSectionExpertList(@RequestParam("sectionId") String sectionId) {
        if (StringUtils.isBlank(sectionId)) {
            return Response.fail("参数不可以为空", Constants.FIVE_HUNDRED_AND_ONE);
        }
        try {
            return Response.ok(beBidResultService.getSectionExpertList(sectionId));
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            return Response.fail("查询评标专家公示失败");
        }
    }

    /**
     * 查询专家评分情况
     *
     * @param sectionId
     * @return
     */
    @ApiOperation(value = "中标结果推送--查询专家评分情况(2019-11-19-v1)", response = Response.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sectionId", value = "标段信息主键", dataType = "String", paramType = "query", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = Constants.FIVE_HUNDRED_AND_ONE, message = "参数不可以为空"),
    })
    @GetMapping(value = "/getExpertScoreList")
    @ResponseBody
    public Response<List<Map<String, Object>>> getExpertScoreList(@RequestParam("sectionId") String sectionId) {
        if (StringUtils.isBlank(sectionId)) {
            return Response.fail("参数不可以为空", Constants.FIVE_HUNDRED_AND_ONE);
        }
        try {
            return Response.ok(beBidResultService.getExpertScoreList(sectionId));
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            return Response.fail("查询专家评分情况失败");
        }
    }

    /**
     * 推送中标结果
     *
     * @param sectionId
     * @return
     */
    @ApiOperation(value = "中标结果推送--推送中标结果(2019-11-21-v1)", response = Response.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sectionId", value = "标段信息主键", dataType = "String", paramType = "query", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = Constants.FIVE_HUNDRED_AND_ONE, message = "参数不可以为空"),
    })
    @GetMapping(value = "/pushBidResult")
    @ResponseBody
    public Response<List<Map<String, Object>>> pushBidResult(@RequestParam("sectionId") String sectionId) {
        if (StringUtils.isBlank(sectionId)) {
            return Response.fail("参数不可以为空", Constants.FIVE_HUNDRED_AND_ONE);
        }
        try {
            Response<String> rsp = beBidResultService.pushBidResult(sectionId);
            if(!rsp.isSuccess()) {
                return Response.fail(rsp.getError());
            }
            return Response.ok();
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            return Response.fail("推送中标结果失败");
        }
    }

    /**
     * 查询中标结果是否已推送成功
     *
     * @param sectionId
     * @return
     */
    @ApiOperation(value = "中标结果推送--查询中标结果推送成功状态(2019-12-21-v1)", response = Response.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sectionId", value = "标段信息主键", dataType = "String", paramType = "query", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = Constants.FIVE_HUNDRED_AND_ONE, message = "参数不可以为空"),
    })
    @GetMapping(value = "/isBidResultPushed")
    @ResponseBody
    public Response<Boolean> isBidResultPushed(@RequestParam("sectionId") String sectionId) {
        if (StringUtils.isBlank(sectionId)) {
            return Response.fail("参数不可以为空", Constants.FIVE_HUNDRED_AND_ONE);
        }
        try {
            BeSectionInfo beSectionInfo = beSectionInfoService.getBeSectionInfoById(sectionId);
            if (beSectionInfo != null && Constants.ONE.equals(beSectionInfo.getIsResultPush())) {
                return Response.ok(true);
            } else {
                return Response.ok(false);
            }
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            return Response.fail("查询中标结果推送状态失败！");
        }
    }
}
